const { app,dialog } = require('electron');
const Client = require('../libs/client');
const ConfigService = require("../libs/configService");
const EVENT = require('./IpcEvent');
/**
 * 构造响应数据
 * @param {返回数据} data 
 * @param {错误消息} error 
 * @param {错误代码} errorcode 
 */
 const _buildResponse = (data, error, errorcode) => {

    return {
        code: error ? (errorcode ? errorcode : 1001) : 1000,
        data: data ? data : "success",
        error: error ? error : null
    };
}

class IpcAdapter{
    constructor(){
        this._configService = new ConfigService();
        this.connectToServer();
    }
    connectToServer(){
        const appConfig = this._configService.loadAppConfig();
        let server = appConfig.uploadServer? appConfig.uploadServer :process.env.SERVER_ADDR;
        console.log("Connect to:"+ server);
        this.client = new Client("ws://"+server);
    }
    OPENCONFIG = ({e,arg})=>{
        //this.client
    }
    FINDALLPROJECTS = ({e, arg })=>{
        this.client.findAllProject().then((res)=>{
            console.log("All project:",res);
            e.sender.send(EVENT.LIST_PROJECTS, res);
        }).catch(err =>{
            console.log("All project:",err);
            e.sender.send(EVENT.LIST_PROJECTS, err);
        });
        
    }
    VIEWPROJECT = ({e,arg})=>{
    
    }
    ADDPROJECT = ({e,arg})=>{
        let project = {projectName:arg.projectName,
            description:arg.description,
            projectType:arg.projectType};
            this.client.addNewProject(project).then((newProject)=>{
            console.log("add project callback:",newProject);
            e.sender.send(EVENT.ADD_PROJECT, newProject);
        }).catch(err =>{
            console.log("All project:",err);
            e.sender.send(EVENT.LIST_PROJECTS, err);
        });
    }
    ADDVERSION = async ({e,arg})=>{
        let version = {projectId:arg.projectId, changeList:arg.changeList, uploadDateTime: arg.uploadDateTime};
        let localFolder = arg.localFolder;
        e.sender.send(EVENT.ADD_VERSION, {'type':'updatepercent',msg:'正在压缩文件。','percent':0});
        this.client.compressPRFile(localFolder).then((fileBuffer)=>{
            if( fileBuffer == null){
                //压缩失败！
                e.sender.send(EVENT.ADD_VERSION, {'type':'updatepercent',msg:'文件压缩失败。','percent':0});
            }else if(typeof(fileBuffer) === 'string'){
                //压缩失败！
                e.sender.send(EVENT.ADD_VERSION, {'type':'updatepercent',msg:'文件压缩失败：'+fileBuffer,'percent':0});
            }else{
                //压缩成功！
                //开始上传版本信息
                this.client.addNewVersion(version).then((newVersion)=>{
                    console.log("add new version callback.",newVersion);
                    if(newVersion.success){
                        const  {newProject,version} = newVersion.data;
                        //添加版本信息成功，开始上传。
                        this.client.uploadPRFile(newProject.projectId,version.versionId,fileBuffer,version.filePath,(result)=>{
                            console.log("upload PRFile callback:",result);
                            if(typeof(result) === 'string'){
                                e.sender.send(EVENT.ADD_VERSION, newVersion);
                            }else{
                                e.sender.send(EVENT.ADD_VERSION_PROCESS, result);
                            }
                        });
                    }else{
                        e.sender.send(EVENT.ADD_VERSION, newVersion);
                    }
                }).catch((err)=>{
                    console.log(err);
                    e.sender.send(EVENT.ADD_VERSION, err);
                });
            }
        });
        
    }
    /****** 以下为公共方法 ********/
    OPENFOLDER_DIALOG = ({e, arg })=>{
        dialog.showOpenDialog({ properties:['openDirectory'] }).then((res=>{
            console.log(res);
            e.sender.send(EVENT.OPEN_FOLDER, res);
        }))
    }
    LOAD_APP_CONFIG = ({e, arg})=>{
        console.log("load config call.")
        const result =  this._configService.loadAppConfig();
        console.log("load config.", result);
        e.sender.send(EVENT.LOAD_APPCONFIG, result);
    }
    SAVE_APP_CONFIG = ({e, arg})=>{
        console.log("save config call.",arg)
        const result = this._configService.saveAppConfig(arg);
        //重新连接服务器
        this.connectToServer();
        console.log("load config.", result);
        e.sender.send(EVENT.SAVE_APPCONFIG, _buildResponse(result));
    }
    routers = {
        [EVENT.OPEN_FOLDER]: this.OPENFOLDER_DIALOG,
        [EVENT.LIST_PROJECTS]: this.FINDALLPROJECTS,
        [EVENT.VIEW_PROJECT]: this.VIEWPROJECT,
        [EVENT.ADD_VERSION]: this.ADDVERSION,
        [EVENT.ADD_PROJECT]: this.ADDPROJECT,
        [EVENT.LOAD_APPCONFIG]:this.LOAD_APP_CONFIG,
        [EVENT.SAVE_APPCONFIG]:this.SAVE_APP_CONFIG,
        [EVENT.COMMON_OPENURL]:null
    }
}
module.exports = IpcAdapter; 

